import {defineStore} from 'pinia';

const useCartStore = defineStore({
    id:"cart",
    state:() => {
        return{
            shopCartList:[],  //购物车数据
            select:[],  //购物车选中的课程，存储id
        }
    },
    actions:{
        //获取购物车数据
        getCartList(list){
            this.shopCartList = list;
            this.select = [];
            list.forEach((item)=>{
                item['select'] = true;
                this.select.push(item.id);
            })
        },

        //课程选项框
        courseChecked(index){
            let id = this.shopCartList[index].id;
            let idx = this.select.indexOf(id);
            if(idx > -1){
                this.shopCartList[index].select = false;
                this.select.splice(idx,1);
            }else{
                this.shopCartList[index].check = true;
                this.select.push( id );
            }
        },

        //全选
        checkedAll(){
            this.select = this.shopCartList.map(v=>{
                v['select'] = true;
                return v.id;
            })
        },
        //全不选
        unCheckedAll(){
            this.shopCartList.forEach(v=>{
                v['select'] = false;
            })
            this.select = [];
        },
    },
    getters:{
        //全选全不选单选框
        isCheckedAll(){
            return this.shopCartList.length==this.select.length?true:false;
        },
        //已选课程数量和总价
        total(){
            let total = {
              price:0,
              number:0
            }
            this.shopCartList.forEach(v=>{
              if( this.select.indexOf( v.id ) != -1 ){
                total.price += v.discountPrice * v.counter;
                total.number = this.select.length;
              }
            })
            return total;
          }
    }
})

export {useCartStore}